package com.wenwu.controller.competence;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import com.wenwu.common.bean.RoleResources;
import com.wenwu.common.bean.User;
import com.wenwu.common.page.PageUtils;
import com.wenwu.common.page.PaginationVO;
import com.wenwu.common.tag.SysConstants;
import com.wenwu.common.utils.JsonUtils;
import com.wenwu.common.utils.MyMd5Utils;
import com.wenwu.service.UserService;

/**
 * @project ATHome-Manager
 * @class UserController.java
 * @author zhujiagui E-mail:<zhujiagui@zkingsoft.com>
 * @date 2015年2月10日 下午3:11:14
 * @description 后台用户管理模块
 */
@Controller(value = "UserController")
@RequestMapping(value = "/user")
public class UserController {
	@Autowired
	private UserService userService;
	Logger log = Logger.getLogger(this.getClass());
	private int result = 0;
	// 用来创建json数据
	private JsonGenerator jsonGenerator = null;

	// 进入页面
	@RequestMapping(value = "/mgr/init")
	public String initUserPage() {
		log.info("进入用户页面...");
		return "user/userlist";
	}

	@RequestMapping(value = "/mgr/tologin")
	public String tologin(Model model) {
		return "user/tologin";
	}

	// 进入角色选择页面
	@RequestMapping(value = "/mgr/showRole")
	public String showRole() {
		log.info("进入角色选择页面...");
		return "user/showrole";
	}

	// 进入角色选择页面
	@RequestMapping(value = "/mgr/login")
	public String login() {
		log.info("进入登陆页面...");
		return "user/login";
	}

	@RequestMapping(value = "/mgr/userform")
	public String userform() {
		return "user/userform";
	}

	// 查询用户数据
	@RequestMapping(value = "/mgr/showList")
	public void showList(Model model, HttpServletRequest request,
			HttpServletResponse response, User user) throws Exception {
		log.info("查询用户数据...");
		PaginationVO pageVo = PageUtils.getPaginationInfo(request);
		try {
			int totalRecord = userService.selectTotalRecord(user, pageVo);// 查询符合条件的个数
			List<User> list = userService.selectUserList(user, pageVo);// 查询符合条件的数据
			pageVo.setList(list);// 将数据设置到PaginationVO对象中
			pageVo.setTotalRecord(totalRecord);
			jsonGenerator = JsonUtils.getJsonGenerator(response);
			jsonGenerator.writeObject(pageVo);// 将PaginationVO对象以json格式写回页面
		} catch (Exception e) {// 异常处理
			log.info(e.getMessage());
			model.addAttribute("errorMsg", "系统异常，请稍后重试!");
		}
	}

	/**
	 * 添加用户信息
	 * 
	 * @param user
	 * @return
	 * @throws IOException
	 * @throws JsonProcessingException
	 */
	@RequestMapping(value = "/mgr/addUser", method = { RequestMethod.POST })
	public void addUser(User user, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		jsonGenerator = JsonUtils.getJsonGenerator(response);
		try {
			if (user.getUserId() == null) {
				java.text.DateFormat format = new java.text.SimpleDateFormat(
						"yyyy-MM-dd HH:mm:ss");
				user.setPassword(MyMd5Utils.getMd5Value(user.getPassword(),
						SysConstants.MD5_KEY));// 密码加密
				user.setUserType("1");// 0：超级用户 1普通用户
				user.setIsLocked("0");// 0：活动 1锁定
				user.setAddTime(format.format(new Date()));
				result = userService.addUser(user);
				jsonGenerator.writeObject("用户添加成功");
			} else {
				result = userService.updateUser(user);
				jsonGenerator.writeObject("用户修改成功");
			}
		} catch (Exception e) {
			jsonGenerator.writeObject("操作失败");
			log.info(e.getMessage());
		} 
	}

	/**
	 * 验证工号是否已经存在
	 * 
	 * @param jobno
	 * @return
	 */
	@RequestMapping(value = "/mgr/validationJobNo")
	public void validationJobNo(HttpServletResponse response,
			@RequestParam(required = false, value = "jobno") String jobno)
			throws Exception {
		log.info("jobno:" + jobno);
		String msg = "false";
		try {
			int result = userService.selectUserByJobNo(jobno);
			if (result > 0) {
				msg = "true";
			}
			jsonGenerator = JsonUtils.getJsonGenerator(response);
			jsonGenerator.writeObject(msg);
		} catch (Exception e) {
			log.info("验证用户账号是否存在 出现异常：" + e.getMessage());
		}
	}

	/**
	 * 查询要修改的用户信息
	 * 
	 * @param response
	 * @param userId
	 * @throws Exception
	 */
	@RequestMapping(value = "/mgr/showUpdate")
	public void showUpdate(HttpServletResponse response,
			@RequestParam(required = false, value = "userId") Integer userId)
			throws Exception {
		if (userId != null) {
			User user = userService.selectUserByKey(userId);
			jsonGenerator = JsonUtils.getJsonGenerator(response);
			jsonGenerator.writeObject(user);
		}
	}

	/**
	 * 批量删除用户信息
	 * 
	 * @param response
	 * @param userId
	 * @throws Exception
	 */
	@RequestMapping(value = "/mgr/deleteUser")
	public void deleteUser(HttpServletResponse response,
			HttpServletRequest request,
			@RequestParam(required = false, value = "key") String key)
			throws Exception {
		log.info("主键：" + key);
		if (key != null) {
			List<String> keys = new ArrayList<String>();
			String[] objs = key.split(",");
			for (String k : objs) {
				keys.add(k);
			}
			jsonGenerator = JsonUtils.getJsonGenerator(response);
			try {
				result = userService.deleteUserByKey(keys);
				jsonGenerator.writeObject("成功删除" + result + "个用户");
			} catch (Exception e) {
				jsonGenerator.writeObject("删除用户失败");
			} 
		}
	}

	/**
	 * 重置密码
	 * 
	 * @param response
	 * @param key
	 * @throws Exception
	 */
	@RequestMapping(value = "/mgr/resetPassword")
	public void resetPassword(HttpServletResponse response,
			HttpServletRequest request,
			@RequestParam(required = false, value = "userId") Integer userId)
			throws Exception {
		jsonGenerator = JsonUtils.getJsonGenerator(response);
		try {
			result = userService.resetPassword(
					MyMd5Utils.getMd5Value("123456", SysConstants.MD5_KEY),
					userId);
			jsonGenerator.writeObject("密码重置成功");
		} catch (Exception e) {
			jsonGenerator.writeObject("密码重置失败");
		} 
	}

	/**
	 * 锁定、解锁用户
	 * 
	 * @param response
	 * @param userId
	 * @throws Exception
	 */
	@RequestMapping(value = "/mgr/updateUserLock")
	public void updateUserLock(HttpServletResponse response,
			HttpServletRequest request,
			@RequestParam(required = false, value = "locked") String locked,
			@RequestParam(required = false, value = "userId") Integer userId)
			throws Exception {
		jsonGenerator = JsonUtils.getJsonGenerator(response);
		try {
			result = userService.updateUserLock(locked, userId);
			jsonGenerator.writeObject("true");
		} catch (Exception e) {
			jsonGenerator.writeObject("false");
		}
	}

	/**
	 * 修改用户密码
	 */
	@RequestMapping(value = "/mgr/updatePwd")
	public void updatePwd(HttpServletResponse response,
			HttpServletRequest request, User user) throws Exception {
		jsonGenerator = JsonUtils.getJsonGenerator(response);
		try {
			user.setPassword(MyMd5Utils.getMd5Value(user.getPassword(),
					SysConstants.MD5_KEY));
			String msg = userService.updatePwd(user);
			jsonGenerator.writeObject(msg);
		} catch (Exception e) {
			jsonGenerator.writeObject(e.getMessage());
		}
	}

	/**
	 * 创建验证码
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/mgr/createCert")
	public void createCert(HttpServletResponse response, HttpSession session)
			throws Exception {
		// 设置浏览器不要缓存此图片
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		response.setContentType("image/jpeg");
		// 创建内存图象并获得其图形上下文
		BufferedImage image = new BufferedImage(60, 20,
				BufferedImage.TYPE_INT_RGB);
		Graphics g = image.getGraphics();
		// 产生随机的认证码并画图
		char[] rands = this.generateCheckCode();
		this.drawBackground(g);
		this.drawRands(g, rands);
		// 结束图像的绘制过程，完成图像
		g.dispose();
		// 将当前验证码存入到Session中
		session.setAttribute("certCode", new String(rands));
		// 将图像输出到客户端
		JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(response
				.getOutputStream());
		encoder.encode(image);
	}

	/**
	 * 产生随机数。
	 * 
	 * @return
	 */
	private char[] generateCheckCode() {
		// 定义验证码的字符表
		String chars = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
		char[] rands = new char[4];
		for (int i = 0; i < 4; i++) {
			int rand = (int) (Math.random() * 28);
			rands[i] = chars.charAt(rand);
		}
		return rands;
	}

	/**
	 * 画随机数。
	 * 
	 * @param g
	 * @param rands
	 */
	private void drawRands(Graphics g, char[] rands) {
		g.setColor(Color.BLACK);
		g.setFont(new Font(null, Font.PLAIN | Font.BOLD, 18));
		// 在不同的高度上输出验证码的每个字符
		g.drawString("" + rands[0], 1, 17);
		g.drawString("" + rands[1], 16, 15);
		g.drawString("" + rands[2], 31, 18);
		g.drawString("" + rands[3], 46, 16);
	}

	/**
	 * 画图片背景。
	 * 
	 * @param g
	 */
	private void drawBackground(Graphics g) {
		g.setColor(new Color(0xDCDCDC));
		g.fillRect(0, 0, 60, 20);
		// 随机产生120个干扰点
		for (int i = 0; i < 120; i++) {
			int x = (int) (Math.random() * 60);
			int y = (int) (Math.random() * 20);
			int red = (int) (Math.random() * 255);
			int green = (int) (Math.random() * 255);
			int blue = (int) (Math.random() * 255);
			g.setColor(new Color(red, green, blue));
			g.drawOval(x, y, 1, 0);
		}
	}

	/**
	 * 登录验证
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/mgr/dologin")
	public void dologin(HttpSession session, HttpServletResponse response,
			HttpServletRequest request,
			@RequestParam(required = false, value = "jobNo") String jobNo,
			@RequestParam(required = false, value = "pwd") String pwd,
			@RequestParam(required = false, value = "code") String code)
			throws Exception {
		User user = null;
		try {
			user = new User();
			user.setJobNo(jobNo);
			user.setPassword(pwd);
			String msg = "";
			jsonGenerator = JsonUtils.getJsonGenerator(response);
			// 获取验证码
			String serverCode = ((String) session.getAttribute("certCode"))
					.toLowerCase();
			// 客户端输入验证码与服务器端验证码不相同
			if (!serverCode.equals(code.toLowerCase())) {
				msg = "您输入的验证码有误！";
			} else {
				user = userService.doLogin(user);
				msg = user.getMsg();
				if ("true".equals(msg)) {
					// 将登录信息放入session
					session.setAttribute(SysConstants.LOGIN_KEY, user);
					// 根据用户角色信息获取角色资源信息
					Map<String, List<RoleResources>> roleResMap = userService
							.getRoleResourceByRoleid(user);
					session.setAttribute(SysConstants.ROLE_RESOURCE_KEY,
							roleResMap);
					result = 1;
				}
			}
			jsonGenerator.writeObject(msg);
		} catch (Exception e) {
			jsonGenerator.writeObject(e.getMessage());
		} 
	}

	// 开发测试快速登录（超级管理员）
	@RequestMapping(value = "/mgr/quikeLogin")
	public void quikeLogin(HttpSession session, HttpServletResponse response)
			throws Exception {
		User user = new User();
		user.setJobNo("super");
		user.setUserName("super");
		user.setRoleName("超级管理员");
		user.setUserId(1);
		user.setUserType("0");
		// 将登录信息放入session
		log.info("快速登录....");
		session.setAttribute(SysConstants.LOGIN_KEY, user);
		jsonGenerator = JsonUtils.getJsonGenerator(response);
		jsonGenerator.writeObject("true");
	}

	/**
	 * 后台用户退出操作
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/mgr/exit")
	public String exit(HttpServletRequest request, HttpSession session)
			throws Exception {
		try {
			User user = (User) session.getAttribute(SysConstants.LOGIN_KEY);
			if (user == null) {
				return "user/login";
			}
			session.setAttribute(SysConstants.LOGIN_KEY, null); // 清空session;
			session.setAttribute(SysConstants.ROLE_RESOURCE_KEY, null);
		} catch (Exception e) {
		}
		return "user/login";
	}
}
